package seller

import (
    "time"
	"dhfshop/controllers/base"
	"dhfshop/models/seller"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type PrintPubController struct {
	base.BaseController
}

// 查询打印模板
func (this *PrintPubController) List() {
	roleId := this.Ctx.Input.GetData("curRoleId").(int)
	query,_, fields, order_by, offset, limit, err := this.GetQueryPara()
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if roleId == 2 {
	    query["status_id"] = "1"
	}
	l, cnt, err := seller.GetAllPrintPubs(query, fields, order_by, offset, limit)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount int64           `json:"total_count"`
		Prints     []*seller.PrintPub `json:"prints"`
	}{TotalCount: cnt, Prints: l}
	this.Data["json"] = r
	this.ServeJSON()
}

// 添加打印模板
func (this *PrintPubController) Add() {
	var v seller.PrintPub
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.TypeId, "type_id")
	valid.Required(v.Content, "content")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	id, err := seller.AddPrintPub(&v)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	v.PrintPubId = int64(id)
	this.Data["json"] = v
	this.ServeJSON()
}

// 更新一个打印模板
func (this *PrintPubController) Update() {
	var v seller.PrintPub
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.PrintPubId, "print_pub_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{"print_pub_id"})
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if len(updateFields) > 0 {
		err := seller.UpdatePrintPub(&v, updateFields...)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		PrintId  int64     `json:"print_pub_id"`
		Modified time.Time `json:"modified"`
	}{PrintId: v.PrintPubId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

// 删除一个打印模板
func (this *PrintPubController) Delete() {
	var v seller.PrintPub
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.PrintPubId, "print_pub_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	err := seller.DeletePrintPub(v.PrintPubId)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		PrintId  int64     `json:"print_pub_id"`
		Modified time.Time `json:"modified"`
	}{PrintId: v.PrintPubId, Modified: time.Now().UTC()}
	this.Data["json"] = r
	this.ServeJSON()
}
